package cn.caskm.souvenirshopsystem.service.impl;

import cn.caskm.souvenirshopsystem.constants.BizConstants;
import cn.caskm.souvenirshopsystem.domain.Result;
import cn.caskm.souvenirshopsystem.domain.dto.PageDTO;
import cn.caskm.souvenirshopsystem.domain.po.GoodsComment;
import cn.caskm.souvenirshopsystem.domain.po.StudentUser;
import cn.caskm.souvenirshopsystem.domain.query.GoodsCommentQuery;
import cn.caskm.souvenirshopsystem.domain.query.PageQuery;
import cn.caskm.souvenirshopsystem.domain.vo.GoodsCommentVO;
import cn.caskm.souvenirshopsystem.exceptions.BizException;
import cn.caskm.souvenirshopsystem.mapper.GoodsCommentMapper;
import cn.caskm.souvenirshopsystem.service.GoodsCommentService;
import cn.caskm.souvenirshopsystem.service.StudentUserService;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class GoodsCommentServiceImpl extends ServiceImpl<GoodsCommentMapper, GoodsComment> implements GoodsCommentService {

    private final StudentUserService userService;

    @Override
    public Result<PageDTO<GoodsComment>> page(PageQuery query) {
        // 获取参数
        Long pageNum = query.getPageNum();
        if (pageNum == null) {
            pageNum = BizConstants.DEFAULT_PAGE_NUM;
        }
        Long pageSize = query.getPageSize();
        if (pageSize == null) {
            pageSize = BizConstants.DEFAULT_PAGE_SIZE;
        }

        // 查询数据
        Page<GoodsComment> page = lambdaQuery()
                .orderByDesc(GoodsComment::getCommentTime)
                .page(new Page<>(pageNum, pageSize));
        
        List<GoodsComment> records = page.getRecords();
        return Result.success(PageDTO.of(records, page.getPages(), page.getTotal()));
    }
    
    @Override
    public Result<List<GoodsComment>> getAll() {
        List<GoodsComment> list = lambdaQuery()
                .orderByDesc(GoodsComment::getCommentTime)
                .list();
        return Result.success(list);
    }

    @Override
    public Result<GoodsComment> detail(Integer id) {
        GoodsComment goodsComment = getById(id);
        if (goodsComment == null) {
            throw new BizException("评论信息不存在");
        }
        return Result.success(goodsComment);
    }

    @Override
    public void saveOrUpdateEntity(GoodsComment goodsComment) {
        if (goodsComment.getCommentId() == null) {
            // 新增评论
            goodsComment.setCommentTime(LocalDateTime.now());
            save(goodsComment);
        } else {
            // 修改评论
            updateById(goodsComment);
        }
    }

    @Override
    public PageDTO<GoodsCommentVO> listGoodsComment(GoodsCommentQuery query) {
        // 获取评论信息
        Integer goodsId = query.getGoodsId();
        Page<GoodsComment> page = lambdaQuery()
                .eq(GoodsComment::getGoodsId, goodsId)
                .orderByDesc(GoodsComment::getCommentTime)
                .page(new Page<>(query.getPageNum(), query.getPageSize()));
        List<GoodsComment> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            return PageDTO.empty();
        }

        // 查询评论中的用户信息
        Set<Integer> userIds = records.stream().map(GoodsComment::getUserId).collect(Collectors.toSet());
        List<StudentUser> studentUsers = userService.listByIds(userIds);
        if (CollUtil.isEmpty(studentUsers)) {
            throw new BizException("用户信息为空");
        }
        Map<Integer, StudentUser> userMap = studentUsers.stream().collect(Collectors.toMap(StudentUser::getId, u -> u));

        // 组装vo
        List<GoodsCommentVO> result = new ArrayList<>(records.size());
        for (GoodsComment comment : records) {
            Integer userId = comment.getUserId();
            StudentUser studentUser = userMap.get(userId);
            if (studentUser == null) {
                log.info("userId = {} 的用户信息从map获取为空", userId);
                continue;
            }
            GoodsCommentVO vo = new GoodsCommentVO();
            vo.setId(comment.getCommentId());
            vo.setGoodsId(comment.getGoodsId());
            vo.setUserId(userId);
            vo.setContent(comment.getComment());
            vo.setPicture(comment.getImage());
            vo.setAvatar(studentUser.getAvatar());
            vo.setCommentTime(comment.getCommentTime());
            vo.setUserName(studentUser.getName());
            vo.setRating(comment.getRating());
            result.add(vo);
        }

        return PageDTO.of(result, page.getPages(), page.getTotal());
    }
}
